import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Input, Modal, Radio, Icon, Select } from 'antd';
import React, { useState, useEffect, useCallback } from 'react';
const FormItem = Form.Item;

const CreateForm = props => {
  const { createModalVisible, selectVipRoomData, onSubmit: handleAdd, onCancel,
    form:{ getFieldDecorator, getFieldValue, setFieldsValue, validateFields, getFieldsValue, resetFields } } = props;
  
  const [terminalCodeArr, setterminalCodeArr] = useState([]);

  const okHandle = () => {
    validateFields((err, fieldsValue) => {
      if (err) return;
      let vipRoomItem = selectVipRoomData.filter((item) => {return item.id === getFieldValue('roomId')})
      let obj = {
        ...fieldsValue,
        portName: vipRoomItem[0].portName,
        name: vipRoomItem[0].roomName,
      }
      handleAdd(obj);
    });
  };
  const formLayout = {
    labelCol: {
      span: 5,
    },
    wrapperCol: {
      span: 15,
    },
  };

  const formItemLayoutWithOutLabel = {
    wrapperCol: {
      xs: { span: 24, offset: 0 },
      sm: { span: 15, offset: 5 },
    },
  };
  //  登机口
  useEffect(() => {
      add();
      resetFields()
  }, []);


  const add = () => {
    setterminalCodeArr([...terminalCodeArr, ''])
  }
  const remove = item => {
    const newterminalCodeArr = JSON.parse(JSON.stringify(getFieldValue('gates')));
    newterminalCodeArr.splice(item, 1);
    setterminalCodeArr(newterminalCodeArr);
    setFieldsValue({
      gates: newterminalCodeArr
    })
  };
  const formItems = useCallback(() => {
    const itemDom = [];
    (terminalCodeArr || []).map((item, index) => {
      itemDom.push((
        <FormItem
          {...(index === 0 ? formLayout : formItemLayoutWithOutLabel)}
          label={index === 0 ? '登机口' : ''}
          required={true}
          key={`gates[${index}${item}]`}
        >
          {getFieldDecorator(`gates[${index}]`, {
            validateTrigger: ['onChange', 'onBlur'],
            initialValue: item,
            rules: [
              {
                validator: async (_, value, callback) => {
                  if (!value) {
                    callback('请输入登机口！')
                    return false
                  } else if (!/^([1-9][0-9]{0,2})$/.test(value)) {
                    callback("请输入1-3位正整数！");
                    return false
                  } else {
                    return true
                  }
                },
              }
            ],
          })(<Input placeholder="请输入" addonAfter="" style={{ width: '87%', marginRight: 8 }} />)}
          {Boolean(index > 0) ? (
            <Icon
              className="dynamic-delete-button"
              type="minus-square-o"
              style={{ fontSize: '26px', verticalAlign: '-0.3em' }}
              onClick={() => remove(index)}
            />
          ) : (<Icon
            className="dynamic-delete-button"
            type="plus-square-o"
            style={{ fontSize: '26px', verticalAlign: '-0.3em' }}
            onClick={() => add()}
          />)}
        </FormItem>
      ))
    });
    return itemDom;
  }, [terminalCodeArr]);

  return (
    <Modal
      destroyOnClose={true}
      title="新建贵宾室规则"
      visible={createModalVisible}
      onOk={okHandle}
      onCancel={() => onCancel()}
    >
      <FormItem key="roomId" {...formLayout} label="贵宾室名称">
        {getFieldDecorator('roomId', {
          rules: [
            {
              required: true,
              message: '请选择贵宾室名称！',
            },
          ],
        })(<Select
            style={{width: 200}}
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent='无贵宾厅数据'
          >
          {selectVipRoomData && selectVipRoomData.length > 0 && 
            selectVipRoomData.map((v, i) => {
              return (
                <Select.Option key={v.id}>{v.roomName}</Select.Option>
              )
            })
          }
        </Select>)}
      </FormItem>
      <FormItem key='capacity' label="容纳人数" {...formLayout}>
        {getFieldDecorator('capacity', {
          validateTrigger: ['onChange', 'onBlur'],
          rules: [
            {
              required: true,
              message: '请输入容纳人数！',
            },
            {
              pattern: /^([1-9][0-9]{0,2})$/,
              message: '请输入1-3位正整数！'
            }
          ],
        })(<Input placeholder="请输入" />)}
      </FormItem>
      <FormItem key='sellNum' label="可售人数" {...formLayout}>
        {getFieldDecorator('sellNum', {
          validateTrigger: ['onChange', 'onBlur'],
          rules: [
            {
              required: true,
              message: '请输入可售人数！',
            },
            {
              validator: (_, value, callback) => {
                if (value && !/^([1-9][0-9]{0,2})$/.test(value)) {
                  callback('请输入1-3位正整数！')
                  return false
                } else if (value && (value - getFieldValue('capacity') > 0)) {
                  callback('可售人数不可大于容纳人数！')
                  return false
                } else {
                  return true
                }
              }
            }
          ],
        })(<Input placeholder="请输入" />)}
      </FormItem>
      {formItems()}
    </Modal>
  );
};

export default Form.create()(CreateForm);
